#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import shutil
import time
from mutagen import File
from tinytag import TinyTag

def get_audio_info_by_tinytag(file_path):
    print("使用 tinytag 库获取音频信息...")
    if not os.path.isfile(file_path):
        print(f"文件 {file_path} 不存在！")
        return None, None, None

    tag = TinyTag.get(file_path)
    
    if tag is None:
        print("无法读取音频文件！")
        return None, None, None

    print(f"文件名: {os.path.basename(file_path)}")
    print(f"文件大小: {os.path.getsize(file_path)} 字节")
    
    # 获取音频标签信息
    title = tag.title
    artist = tag.artist
    album = tag.album
    duration = tag.duration
    
    print(f"歌曲名: {title}")
    print(f"歌手: {artist}")
    print(f"专辑: {album}")
    print(f"持续时间: {duration:.2f} 秒")
    return title, artist, album

def get_audio_info_by_mutagen(file_path):
    print("使用 mutagen 库获取音频信息...")
    if not os.path.isfile(file_path):
        print(f"文件 {file_path} 不存在！")
        return None, None, None

    audio = File(file_path)
    
    if audio is None:
        print("无法读取音频文件！")
        return None, None, None

    print(f"文件名: {os.path.basename(file_path)}")
    print(f"文件大小: {os.path.getsize(file_path)} 字节")
    
    # 获取音频标签信息
    title = audio.get("title", ["未知"])[0]
    artist = audio.get("artist", ["未知"])[0]
    album = audio.get("album", ["未知"])[0]
    duration = audio.info.length if audio.info else "未知"
    
    print(f"歌曲名: {title}")
    print(f"歌手: {artist}")
    print(f"专辑: {album}")
    print(f"持续时间: {duration:.2f} 秒")
    return title, artist, album

def get_audio_info(file_path):
    title, artist, album = get_audio_info_by_mutagen(file_path)
    if artist == "未知":
        title, artist, album = get_audio_info_by_tinytag(file_path)
    return title, artist, album

def classify_audio_by_artist(autdio_path, dest_dir):
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    if not os.path.exists(os.path.join(dest_dir, "unknown")):
        os.makedirs(os.path.join(dest_dir, "unknown"))
    title, artist, album = get_audio_info(autdio_path)
    if title is None:
        dest_path = os.path.join(dest_dir, "unknown", os.path.basename(autdio_path))
        if os.path.exists(dest_path):
            print(f"{title} 已存在于 {dest_path}")
            shutil.rmtree(autdio_path)
        else:
            shutil.move(autdio_path, dest_path)
        print(f"未知音乐文件已移动到 {dest_path}")
        return
    if not os.path.exists(os.path.join(dest_dir, artist.strip())):
        os.makedirs(os.path.join(dest_dir, artist.strip()))
    dest_path = os.path.join(dest_dir, artist.strip(), os.path.basename(autdio_path))
    if os.path.exists(dest_path):
        print(f"{title} 已存在于 {dest_path}")
        timestemp = time.strftime("%Y%m%d%H%M%S", time.localtime())
        name, ext = os.path.splitext(dest_path)
        dest_path = f"{name}_{timestemp}{ext}"
    shutil.move(autdio_path, dest_path)
    print(f"已将 {title} 移动到 {dest_path}")

def classify_all_audio_by_artist(audio_dir, dest_dir):
    if not os.path.exists(audio_dir):
        print(f"目录 {audio_dir} 不存在！")
        return
    if len(os.listdir(audio_dir)) == 0:
        print(f"目录 {audio_dir} 为空！")
        shutil.rmtree(audio_dir)
        return
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)
    for file_name in os.listdir(audio_dir):
        file_path = os.path.join(audio_dir, file_name)
        # if os.path.isfile(file_path) and file_path.endswith((".mp3", ".wav", ".flac", ".ape", ".dts")):
        if os.path.isfile(file_path): 
            print(f"正在处理 {file_name}...")
            classify_audio_by_artist(file_path, dest_dir)
        else:
            sub_dir = os.path.join(audio_dir, file_name)
            classify_all_audio_by_artist(sub_dir, dest_dir)

if __name__ == "__main__":
    src_dir = r"H:/demo"
    dest_dir = r"I:/分类音乐/歌手"
    classify_all_audio_by_artist(src_dir, dest_dir)


